﻿using gecommon;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace geagent
{
    //管理Agent
    public class AgentManager
    {
        //不用WaitFreeQueue节省一个线程
        private LockQueue<object> _loginout = new LockQueue<object>();//专门用于处理登陆登出消息队列

        //角色ID=>Agent 特殊的ID为0的Agent 用来处理通用操作比如账户登陆后查询角色信息
        private ConcurrentDictionary<long, Agent> _agents = new ConcurrentDictionary<long, Agent>();

        private Thread _thread;

        public void Start()
        {
            Task.Run(() => HandleLoginoutAsync());
            _thread = new Thread(ConsumeLoop);
            _thread.Start();
        }

        //服务器运行过程中不会退出 暂时不考虑优雅退出
        private void ConsumeLoop()
        {
            var ch = Channel.Instance();
            while (true)
            {
                object req = ch.Recv4Agent();
                //根据req来实现不同的功能 如果是角色登陆登出的请求直接转发到专门队列处理
                //防止堵塞消息分发
                //if(req as Login != null)
                //  _loginout.Enqueue(req)
            }
        }

        private async Task HandleLoginoutAsync()
        {
            while (true)
            {
                //每50ms醒1次处理登陆登出消息
                await Task.Delay(50);
                //根据角色登陆登出进行处理 添加删除Agent
                while (!_loginout.empty())
                {
                    var req = _loginout.Dequeue();
                }
            }
        }
    }
}
